<template>
	<view class="h-fill pos-real">
		<u-navbar :title="title" :background="{ 'background-image': 'linear-gradient(to right, #434AD8, #8E77F5)' }"
			:borderBottom="false" backIconColor="#fff" titleColor="#fff" v-if="from === 'gameroom'"></u-navbar>

		<map id="map" class="top-fixed map" :style="{ height: mapHeight + 'px' }" :markers="markers"
			:show-location="true" :longitude="centerLocation.longitude" :latitude="centerLocation.latitude"
			@updated="updated" @tap="handleMapTap" @markertap="clickMarkerTap" @regionchange="regionchange">
		</map>

		<!-- 搜索框 -->
		<view :class="['search', 'h-box', 'justify-between', popupVisible ? 'search-transition' : '']"
			@click="navToSearch">
			<view class="flex-extend">
				<view v-if="searchValue" class="u-line-1 ellipsis-1">{{ searchValue }}</view>
				<view v-else style="color: #C8C8C8;">搜索位置查找附近门店</view>
			</view>
			<view class="h-box">
				<view v-if="searchValue" class="search-clear l-mg" @click.stop="searchValue = ''">×</view>
				<image src="/static/img/main_ic_sousuo@2x.png" style="width: 36rpx; height: 36rpx;" class="l-mg">
				</image>
			</view>
		</view>

		<!-- 气泡 -->
		<view class="bubble" v-show="showBubble" @click="clickBubble">
			<view v-if="currentMarkers"
				:class="['customCallout2', 'h-box', currentMarkers.calloutText.address === list[0].address ? 'border-red' : 'border-blue']">
				<image :src="currentMarkers.calloutText.thumbnail" class="img"></image>
				<view class="flex-v justify-between mg-l-xs store-text">
					<view class="h-box justify-between">
						<view class="text-title flex-extend uni-ellipsis ellipsis-1">
							{{ currentMarkers.calloutText.name }}</view>
						<image src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_dingwei_juli@2x.png" style="width: 24rpx; height: 24rpx;"></image>
						<view class="uni-text-gray u-line-1 ellipsis-1">{{ currentMarkers.calloutText.distance }}</view>
					</view>
					<view class="uni-text-gray u-line-2">{{ currentMarkers.calloutText.address }}</view>
				</view>
			</view>
		</view>

		<!-- 弹窗 -->
		<view class="flex-v" :class="['popup', 'content', popupVisible ? 'popup-transition' : '']">
			<view class="btn-popup v-box justify-center" style="background-color: #FFFFFF;"
				@click="openOrClose('popup')">
				<view class="line"></view>
			</view>
			<!-- <view v-if="selectedStore" class="h-fill flex-v justify-between pad-l-base pad-r-base flex-extend" :style="{height: scrollViewHeight + 'px'}"> -->
			<view v-if="selectedStore" class="h-fill flex-v justify-between flex-extend pad-l-base pad-r-base">
				<view class="h-box">
					<image style="width: 36rpx;height: 36rpx;"
						src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/main_ic_baojian@2x.png">
					</image>
					<view class="mg-l-xs h-box flex-extend">
						<view>选择包间</view>
						<view class="pad-l-xs pad-r-xs">|</view>
						<view style="color: #FF5673;" v-if="selectedStore && selectedStore.roomList.length">
							收费每人￥{{ selectedRoom.price / 100 || 0 }}元</view>
						<view style="color: #FF5673;" v-else>收费每人￥{{ selectedStore.unifyPrice / 100 || 0 }}元</view>
					</view>
					<view @click="navToRoomDetail" class="h-box">
						<view class="uni-text-gray">查看图片</view>
						<image src="/static/img/right_arrow.png" style="width: 14rpx; height: 24rpx;"></image>
					</view>
				</view>
				<view class="flex-extend">
					<scroll-view scroll-x class="room-scroll">
						<view class="room-item-wrapper pad-t-xs">
							<view v-for="(item,idx) in selectedStore.roomList" :key="idx" class="room-item"
								:class="{'room-item-active' : idx == selectedRoomIdx}" @click="handleRoomClick(idx)">
								{{item.name}}
							</view>
						</view>
					</scroll-view>
				</view>
				<view class="bottom-btn">
					<template v-if="from === 'tearoom'">
						<button @click="navToOrder"
							:class="['u-reset-button', 'btn-confirm', selectedRoomIdx === -1 ? 'confirm-button-not' : '']">发起</button>
					</template>
					<template v-else>
						<view v-if="selectMode">
							<button @click="confirmRoom" v-if="selectedStore && selectedStore.roomList.length"
								:disabled="selectedRoomIdx == -1" class="u-reset-button btn-confirm">确定</button>
							<button @click="confirmRoom" v-else class="u-reset-button btn-confirm">确定</button>
						</view>
						<view v-else>
							<button @click="navToOrder" v-if="selectedStore && selectedStore.roomList.length"
								:disabled="selectedRoomIdx == -1" class="u-reset-button btn-confirm">确定</button>
							<button @click="navToOrder" v-else class="u-reset-button btn-confirm">确定</button>
						</view>
					</template>
				</view>
			</view>
		</view>

		<!-- 控件：定位 -->
		<image src="/static/img/ic_back-location.png"
			:class="['control', 'control-location', popupVisible ? 'control-transition' : '']"
			@click="clickControlTap('backLocation')">
		</image>

		<!-- 控件：客服 -->
		<image src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/service-btn-location.png"
			:class="['control', 'control-service', popupVisible ? 'control-transition' : '']"
			@click="clickControlTap('serviceControl')">
		</image>
		<u-modal v-model="showServiceControl" :show-title="false" confirm-text='关闭' mask-close-able>
			<view class="addService pos-real u-p-l-30 u-p-t-30 u-p-b-30">
				<view class="uni-flex align-center">
					<image class="logo" :src="$getCloudStorageUrl('/ic_disankongjian@2x.png')" mode="aspectFit"></image>
					<view class="uni-flex-extend uni-flex uni-column">
						<text>第三空间客服</text>
						<text class="uni-text-gray">客服在线时间</text>
						<text class="uni-text-gray">10:00-12:00, 14:00-18:00</text>
					</view>
				</view>
				<view class="btn-copy pos-abs-rt mg-t-sm uni-flex align-center" @click="clickaddService">
					<image src="
https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_fuzhi@2x.png" mode="aspectFit"></image>
					<text>复制微信号</text>
				</view>
			</view>
		</u-modal>

		<!-- 控件：订单 -->
		<image src="/static/img/order-btn-location.png"
			:class="['control', 'control-order', popupVisible ? 'control-transition' : '']"
			@click="clickControlTap('orderControl')">
		</image>
	</view>
</template>

<script>
	const db = uniCloud.database()
	const dbCmd = db.command
	const $ = dbCmd.aggregate

	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"

	import {
		reverseGeocoder
	} from "@/api/platform/user.js"

	var sysInfo;

	export default {
		name: 'map-com',
		data() {
			return {
				searchValue: '',

				searchLocation: null,
				centerLocation: {},

				showServiceControl: false,
				popupVisible: false,
				popupHeight: 180,
				scrollViewHeight: 0,
				mapHeight: 600,
				navHeight: 44,

				isClickControl: false,
				isClickTop: true,

				showBubble: false,
				currentMarkers: null,

				markers: [],
				selectedStore: null,
				selectedRoomIdx: -1,
				list: [],

				selectMode: false,
				from: 'tearoom',
				
				initialized: false
			}
		},
		created() {
			// console.clear()

			uni.showLoading({
				mask: true
			})

			sysInfo = uni.getSystemInfoSync();
			this.isAndroid = sysInfo.platform.match(/Android/ig)
			//#ifdef MP
			let rect = uni.getMenuButtonBoundingClientRect();
			this.navHeight = (rect.top - sysInfo.statusBarHeight) * 2 + rect.height;
			//#endif
			this.mapHeight = sysInfo.windowHeight - sysInfo.statusBarHeight - this.navHeight;
			// console.log("mapHeight: ",this.mapHeight);
			// this.popupHeight = sysInfo.windowHeight * 0.26;
			// this.popupHeight = 180;
			this.scrollViewHeight = this.popupHeight - 35 - sysInfo.safeAreaInsets.bottom
		},
		// onLoad(e) {
		//   if (e.selectMode) {
		//     this.selectMode = true
		//   }
		//   this.from = e?.from || 'tearoom'
		// },
		// async onReady() {
		//   this.from = this.from || 'tearoom'
		//   await this.getListData()
		// },
		computed: {
			...mapState(['userLocation']),

			title() {
				if (this.selectMode) {
					return '选择门店'
				}
				return '门店'
			},
			selectedRoom() {
				if (this.selectedStore && this.selectedStore.roomList && this.selectedRoomIdx != -1) {
					return this.selectedStore.roomList[this.selectedRoomIdx]
				}
				return {}
			}
		},
		mounted() {
		},
		// watch: {
		//   'userLocation'(newValue, oldValue) {
		//     if (this.userLocation) {
		//       this.getListData()
		//     }
		//   }
		// },
		methods: {
			navToLocation() {
				let item = this.selectedStore
				uni.openLocation({
					longitude: item.location.coordinates[0],
					latitude: item.location.coordinates[1],
					address: item.address || '',
					success: (res) => {
						this.$log("打开地图查看位置成功", res);
					},
					fail: (err) => {
						this.$log("打开地图查看位置失败", err);
					}
				})
			},
			makePhoneCall() {
				let item = this.selectedStore
				uni.makePhoneCall({
					phoneNumber: item.phone
				})
			},

			async navToSearch() {
				if (!this.isAndroid) {
					await this.verifyLocation()
				}

				let longitude = this.userLocation.longitude
				let latitude = this.userLocation.latitude
				if (this.searchLocation) {
					longitude = this.searchLocation.longitude
					latitude = this.searchLocation.latitude
				}
				uni.chooseLocation({
					longitude,
					latitude,
					success: async (res) => {
						// console.log("搜索回调: ",res);
						this.searchValue = res.name
						this.searchLocation = {
							longitude: res.longitude,
							latitude: res.latitude
						}
						this.searchLocation.adCode = await reverseGeocoder(this.searchLocation)
						this.centerLocation = this.searchLocation
						this.getListData()
					},
					fail: (err) => {
						console.log("选择位置遇到错误: ", err);
					}
				})
			},

			navToOrder() {
				if (this.from === 'tearoom' && this.selectedRoomIdx === -1) {
					uni.showToast({
						title: '请选择包间',
						icon: 'none'
					})
					return
				}
				let data = JSON.stringify({
					storeId: this.selectedStore._id,
					storeName: this.selectedStore.name,
					roomIdx: this.selectedRoomIdx,
					from: this.from
				})
				uni.navigateTo({
					url: '/pagesSubscribe/create-order?data=' + encodeURIComponent(data)
				})
			},

			navToRoomDetail() {
				let that = this
				uni.navigateTo({
					url: `/pagesSubscribe/store-room?storeId=${ this.selectedStore._id }&currentRoomId=${ this.selectedStore.roomList[this.selectedRoomIdx]?._id }&from=${ this.from }`,
					events: {
						selectRoom: function(id) {
							for (let i = 0; i < that.selectedStore.roomList.length; i++) {
								if (that.selectedStore.roomList[i]._id !== id) continue
								that.selectedRoomIdx = i
								return
							}
						}
					}
				})
			},
			confirmRoom() {
				this.getOpenerEventChannel().emit('selected', this.selectedStore, this.selectedStore.roomList[this
					.selectedRoomIdx])
				uni.navigateBack()
			},
			handleRoomClick(idx) {
				if (this.selectedRoomIdx == idx) {
					this.selectedRoomIdx = -1
				} else {
					this.selectedRoomIdx = idx
				}
			},

			updated(e) {
				if (!this.initialized) {
					this.getListData()
				}
				// this.getListData()
				// if (!this.isClickControl) {
				// 	this.clickMarkerTap({
				// 		detail: {
				// 			markerId: 0,
				// 			from: 'code'
				// 		}
				// 	})
				// 	this.isClickTop = false
				// }
				// setTimeout(() => this.isClickControl = false, 1000)
			},
			handleMapTap() {
				this.showBubble = false
				this.popupVisible = false
			},
			regionchange(e) {
				// this.showBubble = false
				// this.popupVisible = false
				// if (e.type === 'begin' && !this.isClickTop) {
				// 	// this.showBubble = false
				// }
				// this.$nextTick(() => {
				// 	this.isClickTop = false
				// })
			},

			updateCenterLocation() {
				this.centerLocation = null
				let newUserLocation = null
				uni.getLocation({
					type: "gcj02",
					success: res => {
						newUserLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						}
						this.setCurrentRegion({
							newUserLocation
						})
					},
					fail: err => {
						console.log("获取位置失败: ", err);
						newUserLocation = this.userLocation
					},
					complete: () => {
						this.searchLocation = null
						this.searchValue = ''
						this.centerLocation = newUserLocation
						this.getListData('controlTap')
					}
				})
			},
			clickaddService() {
				// #ifndef H5
				uni.setClipboardData({
					data: "i3d008",
					success: () => {
						uni.showModal({
							title: "提示",
							content: "客服微信已复制，请去微信添加",
							confirmText: "知道了",
							showCancel: false
						})
					}
				})
				// #endif
			},
			clickControlTap(controlId) {
				switch (controlId) {
					case 'backLocation':
						this.isClickControl = true
						this.updateCenterLocation();
						break;
					case "serviceControl":
						this.showServiceControl = true
						break;
					case "orderControl":
						uni.navigateTo({
							url: `/pagesFoo/order/order`
						})
						break;
					default:
						break;
				}
			},

			clickMarkerTap(e) {
				if (!this.list.length) return

				let idx = e.detail.markerId;
				this.selectedRoomIdx = -1
				this.selectedStore = this.list[idx];
				this.getRoomList('marker')

				this.centerLocation = null
				this.$nextTick(() => {
					if (e?.from !== 'code') {
						this.centerLocation = {
							longitude: this.selectedStore.location.coordinates[0],
							latitude: this.selectedStore.location.coordinates[1]
						}
						this.isClickTop = true
					}
					this.showBubble = true
				})

				this.currentMarkers = this.markers[idx]

				this.openOrClose('marker')
			},
			clickBubble() {
				uni.navigateTo({
					url: `/pagesSubscribe/store-detail?storeId=${ this.selectedStore._id }&from=${ this.from }`
				})
			},

			openOrClose(from) {
				switch (from) {
					case 'marker':
						this.popupVisible = true
						break;
					case 'popup':
						this.popupVisible = !this.popupVisible
						break;
					default:
						break;
				}
			},

			formatDistance(meters) {
				if (meters < 1000) {
					return `${Math.floor(meters)}m`;
				} else {
					return `${Math.floor(meters / 1000)}km`;
				}
			},

			async getRoomList(from) {
				if (this.selectedStore && this.selectedStore.roomList) return

				uni.showLoading({
					mask: true
				})

				try {
					let list = await this.$dbHelper.getList("t3ds-store-room", {
						where: {
							storeId: this.selectedStore._id,
							type: this.from
						}
					})
					this.$set(this.selectedStore, 'roomList', list)

					if (from === 'marker') {
						uni.hideLoading()
					}
				} catch (e) {
					uni.hideLoading()
					console.log("查询包间出错: ", e);
				}
			},
			async getListData(from = '') {
				this.list = []
				this.selectedStore = []
				// this.popupVisible = false
				this.markers = []

				try {
					let query = {
						enabled: true,
						joinSharePlan: true
					}
					if (this.from === 'tearoom') {
						query.cooperationMode = dbCmd.neq('school')
					}

					let searchRes = null
					// 获取搜索点附近门店
					if (this.searchLocation) {
						query['region.city.value'] = this.searchLocation.adCode
						let res = await db.collection("t3ds-store")
							.aggregate()
							.geoNear({
								near: new db.Geo.Point(this.searchLocation.longitude, this.searchLocation
									.latitude),
								query,
								spherical: true,
								distanceField: 'distance'
							})
							.project({
								thumbnail: $.arrayElemAt(['$photos', 0]),
								name: 1,
								address: 1,
								distance: 1,
								location: 1,
								unifyPrice: 1,
								phone: 1
							})
							.sort({
								distance: 1
							})
							.limit(100)
							.end()
						searchRes = res.result.data
						// console.log("searchRes: ", searchRes);
						let storesId = searchRes.map(item => item._id)
						query._id = dbCmd.in(storesId)
					}

					let region = uni.getStorageSync('currentRegion')
					query['region.city.value'] = region.city.value
					let res = await db.collection("t3ds-store")
						.aggregate()
						.geoNear({
							near: new db.Geo.Point(this.userLocation.longitude, this.userLocation.latitude),
							query,
							spherical: true,
							distanceField: 'distance'
						})
						.project({
							thumbnail: $.arrayElemAt(['$photos', 0]),
							name: 1,
							address: 1,
							distance: 1,
							location: 1,
							unifyPrice: 1,
							phone: 1
						})
						.sort({
							distance: 1
						})
						.limit(100)
						.end()

					this.list = res.result.data
					if (this.list.length) {
						if (from !== 'controlTap') {
							this.centerLocation = {
								longitude: this.list[0].location.coordinates[0],
								latitude: this.list[0].location.coordinates[1]
							}
						}
						this.selectedStore = this.list[0]
						this.markers = this.list.map((item, index) => {
							let display = 'BYCLICK'
							let bgColor = '#6565fe99'
							let iconPath = '/static/img/landmark-blue.png'
							let width = uni.upx2px(44)
							let height = uni.upx2px(58)
							let joinLabel = ` | `
							let fontSize = 12
							let padding = 5
							let anchorX = 0

							// if (index === 0) {
							//   display = 'ALWAYS'
							//   bgColor = '#fe000400'
							// }
							if (index === 0) {
								bgColor = '#fe00044c'
								iconPath = '/static/img/landmark-red.png'
							}

							let distance = this.formatDistance(item.distance)

							if (this.isAndroid) {
								anchorX = -((item.name.length + (distance.length + joinLabel.length) / 2) *
									fontSize + padding * 2 + width - 4) / 2 // 减4向右移
							}

							return {
								id: index,
								longitude: item.location.coordinates[0],
								latitude: item.location.coordinates[1],
								iconPath,
								width,
								height,
								calloutText: {
									thumbnail: item.thumbnail,
									name: item.name,
									distance,
									address: item.address
								},
								customCallout: {
									display,
									anchorX: 0,
									anchorY: -12
								},
								label: {
									content: item.name + joinLabel + distance,
									color: '#ffffffe5',
									borderRadius: 16,
									bgColor,
									padding,
									anchorX,
									anchorY: 10,
									textAlign: 'center',
									fontSize
								}
							}
						})
						this.popupVisible = true
						this.showBubble = true
						this.currentMarkers = this.markers[0]
						await this.getRoomList()
					}
					// console.log("list: ", this.list);
					uni.hideLoading()
					this.initialized = true
				} catch (e) {
					uni.hideLoading()
					console.log("查询出错: ", e);
				}
			},

			...mapActions(['verifyLocation']),
			...mapMutations(['setCurrentRegion'])
		}
	}
</script>

<style lang="scss" scoped>
	$transition: transform 200ms linear;

	.ellipsis-1 {
		white-space: nowrap !important;
	}

	/* 搜索框 */
	.search {
		z-index: 999;
		width: calc(100% - 60rpx);
		height: 68rpx;
		line-height: 68rpx;
		padding: 0 30rpx;
		border-radius: 36rpx;
		background-color: #FFFFFF;
		position: relative;
		left: 30rpx;
		top: 20rpx;

		.search-clear {
			width: 36rpx;
			height: 36rpx;
			line-height: 36rpx;
			font-size: 36rpx;
			text-align: center;
		}
	}

	/* 气泡 */
	.bubble {
		width: 690rpx;
		height: 186rpx;
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -80%);
		z-index: 999;

		.border-blue {
			border: 1px solid #6565fe;
		}

		.border-red {
			border: 1px solid #fe0004;
		}

		.customCallout1 {
			width: 130rpx;
			height: 82rpx;
			border-radius: 20rpx;
			border: 1px solid #fe000499;
		}

		.customCallout2 {
			border-radius: 20rpx;
			padding: 30rpx;
			background-color: #FFFFFF;
			// z-index: 555;

			.img {
				width: 180rpx;
				height: 126rpx;
				border-radius: 20rpx;
			}

			.store-text {
				flex: 1;
				height: 126rpx;
			}
		}

		view {
			white-space: normal;
			line-height: 1.5;
		}
	}

	/* 弹窗 */
	$popup-heigth: 310rpx;
	$popup-line-heigth: 60rpx;
	$popup-content-heigth: $popup-heigth - $popup-line-heigth;

	.popup {
		z-index: 999;
		height: $popup-heigth;
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #FFFFFF;
		border-top-left-radius: 60rpx;
		border-top-right-radius: 60rpx;
		padding-bottom: 30rpx;

		transform: translateY($popup-heigth);
		transition: $transition;

		.btn-popup {
			background-color: #D61719;
			border-top-left-radius: 60rpx;
			border-top-right-radius: 60rpx;
			height: $popup-line-heigth;

			.line {
				width: 106rpx;
				height: 6rpx;
				background: #DFDFDF;
				border-radius: 3rpx;
			}
		}

		.room-scroll {
			width: 100%;
			padding: 15rpx 0;
			display: flex;
			flex-wrap: wrap;
			flex-direction: row;
			overflow-y: scroll;

			.room-item-wrapper {
				display: flex;
				flex-direction: row;
				flex-wrap: nowrap;
				align-items: center;

				.room-item {
					min-width: 120rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
					background-color: #EFF1F7;
					border-radius: 20rpx;
					margin: 0 20rpx 10rpx 0;
					padding: 0 25rpx;
				}

				.room-item-active {
					background-color: #6565FE;
					color: #FFFFFF;
				}
			}
		}

		.bottom-btn {
			.btn-confirm {
				width: 434rpx;
				height: 88rpx;
				line-height: 88rpx;
				background: #FF5673;
				border-radius: 49rpx;
				color: #FFFFFF;
				margin-bottom: constant(safe-area-inset-bottom);
				margin-bottom: env(safe-area-inset-bottom);
			}

			.confirm-button-not {
				background-color: #f7f7f7 !important;
				color: rgba(0, 0, 0, .3) !important;
			}
		}
	}

	.popup-transition {
		transform: translateY(0);
	}

	/* 控件 */
	$control-loc: -30rpx;
	$control-transition: $control-loc - $popup-heigth;

	.control {
		z-index: 999;
		position: fixed;

		transform: translateY($control-loc);
		transition: $transition;
	}

	.control-location {
		width: 60rpx;
		height: 60rpx;
		left: 45rpx;
		bottom: 120rpx;
	}

	.control-service {
		width: 90rpx;
		height: 90rpx;
		left: 30rpx;
		bottom: 0;
	}

	.control-order {
		width: 90rpx;
		height: 90rpx;
		right: 30rpx;
		bottom: 0;
	}

	.control-transition {
		transform: translateY($control-transition);
	}

	/* 添加客服 */
	.addService {
		.logo {
			width: 120rpx;
			height: 120rpx;
			margin-right: 20rpx;
		}

		.btn-copy {
			background-color: #F4F4F4;
			color: #999999;
			padding: 0 20rpx;
			height: 60rpx;
			line-height: 60rpx;
			align-self: flex-start;
			border-top-left-radius: 60rpx;
			border-bottom-left-radius: 60rpx;

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
	}
</style>
